# Copyright 2025 Yan Mingshu <yms_hi@outlook.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import inquirer_console as ic
import click
from loguru import logger
import os
import regex
import shutil
import os

TOOL_VERSION = 1

def printInfo():
    # print('''1''')
    ...

@click.command()
def tui():
    printInfo()
    
    input = ic.Input("tar.gz file",filter=lambda p: os.path.abspath(p),validate=lambda p: True if os.path.exists(p) else "文件不存在").prompt()
    ver,target = getVersion(os.path.basename(input))
    match target:
        case "x64":
            target = "amd64"
    
    ver = ic.Input("Cangjie version",default= ver if ver else None).prompt()
    
    target = ic.Input("Cangjie target [ amd64 |arm64 | ... ]",default=target if target else "amd64").prompt()
    
    channel:str = ic.Input("Cangjie Channel [STS|LTS|Canary]",default="STS").prompt()
    channel = channel
    
    build(input,ver,target,y=False,channel=channel)
    

def getVersion(name:str) -> tuple[str,str]:
    f = regex.match(r"[Cc]angjie-(?<version>\d(?:.\d+)*)?-linux_(?<target>[\dx]+).tar.gz",name)
    if f==None:
        return "",""
    return f.group("version"),f.group("target")
    

def build(src:str,ver:str,target:str,y:bool,channel:str) -> None:
    output = f"cangjie-{channel.upper()}-{ver}-{target}.deb"
    
    logger.info(f"Build Config")
    logger.info(f"Source:  {src}")
    logger.info(f"Output:  {os.path.abspath(f"./dist/{output}")}")
    logger.info(f"Channel: {channel}")
    logger.info(f"Version: {ver}")
    logger.info(f"Package Target: {target}")
    
    if not y:
        if not ic.Confirm("是否构建").prompt():
            exit(1)
    
    if os.path.exists("cache"):
        shutil.rmtree("cache")
    
    if os.path.exists(f"./dist/{output}"):
        os.remove(f"./dist/{output}")
    
    logger.info("创建缓存文件夹")
    os.makedirs("./cache/pkg/opt")
    
    logger.info(f"解压压缩包： {src}")
    shutil.unpack_archive(src,"./cache/unpack")
    shutil.move("./cache/unpack/cangjie",f"./cache/pkg/opt/cangjie-{channel.lower()}/")
    
    logger.info("创建控制文件")
    os.mkdir("./cache/pkg/DEBIAN/")
    with open("./cache/pkg/DEBIAN/control","+a",encoding="utf-8") as f:
        f.write('''Package: cangjie-{0}
Version: {1}-{2}
Section: devel
Architecture: {3}
Maintainer: Yan Mingshu <yms_hi@Outlook.com>
Depends: binutils, libc-dev, libc++-dev ,libgcc-7-dev
Suggests: openssl (>=3.0.7)
Homepage: https://cangjie-lang.cn
Description: A new-generation programming language oriented to full-scenario intelligence.
'''.format(channel.lower(),ver,TOOL_VERSION,target))
    
    command = "cd ./cache\ndpkg-deb --root-owner-group --build pkg"
    logger.info(f"Run command: {command.replace("\n"," && ")}")
    r = os.system(command)
    if r:
        logger.error(f"Command failed! Return code: {r}")
        exit(1)

    
    if not os.path.exists("./dist"):
        os.mkdir("./dist")
    
    
    shutil.move("./cache/pkg.deb",f"./dist/{output}")
    
    logger.info("清理缓存")
    shutil.rmtree("./cache")
    
    logger.success("构建成功")
    logger.success(f"构建产物: {os.path.abspath(f"./dist/{output}")}")
    

if __name__ == '__main__':
    tui()
